import React from 'react';
import { Avatar, message as antMessage } from 'antd';
import { UserOutlined, RobotOutlined, CopyOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeHighlight from 'rehype-highlight';
import { Message } from '@/types/chat';


interface MessageCardProps {
  message: Message;
  typewriterText: string;
}

/**
 * Markdown渲染核心组件
 */
const MarkdownRenderer = ({ content }: { content: string }) => {
  return (
    <ReactMarkdown
      remarkPlugins={[remarkGfm]}
      rehypePlugins={[rehypeHighlight]}
      components={{
        code({ node, className, children, ...props }) {
          const match = /language-(\w+)/.exec(className || '');
          const isInline = !match;
          if (isInline) {
            return <code className={className} {...props}>{children}</code>;
          }
          const language = match ? match[1] : 'text';
          return (
            <div className="code-block">
              <div className="code-header">
                <span className="code-language">{language}</span>
                <button
                  className="code-copy"
                  onClick={() => {
                    const extractText = (nodes: any[]): string => {
                      return nodes.map(node => {
                        if (node.type === 'text') return node.value;
                        if (node.children && Array.isArray(node.children)) return extractText(node.children);
                        return '';
                      }).join('');
                    };
                    const codeToCopy = extractText(node.children);
                    navigator.clipboard.writeText(codeToCopy);
                    antMessage.success('代码已复制');
                  }}
                >
                  <CopyOutlined />
                </button>
              </div>
              <pre className={className}><code {...props}>{children}</code></pre>
            </div>
          );
        },
        a({ children, href, ...props }) {
          return <a href={href} target="_blank" rel="noopener noreferrer" {...props}>{children}</a>;
        }
      }}
    >
      {content}
    </ReactMarkdown>
  );
};

/**
 * 单条消息展示组件
 */
const MessageCard: React.FC<MessageCardProps> = ({ message, typewriterText }) => {
  const { role, content, isStreaming } = message;

  return (
    <div className={`message-wrapper ${role}`}>
      <div className="message-avatar">
        <Avatar icon={role === 'user' ? <UserOutlined /> : <RobotOutlined />} />
      </div>
      <div className="message-content-wrapper">
        {isStreaming ? (
          <div className="streaming-content">
            <span>{typewriterText}</span>
            <span className="typing-cursor">|</span>
          </div>
        ) : (
          <MarkdownRenderer content={content} />
        )}
      </div>
    </div>
  );
};

export default MessageCard;
